<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="main" my_attribute="hello" style="color: red;" onclick="console.log('get')">main</div>

    <script>
        const divmain = document.getElementById('main')
        console.log(divmain.attributes) // NamedNodeMap[] 类似NodeList的集合

        // 获取id属性的值 getNamedItem('id_name')  或者是  element.attributes['id_name']
        // 设置属性的值: element.attributes['id_name'] = 新值
        let id = divmain.attributes.getNamedItem('id').nodeValue
        console.log(id) //  main
        console.log(divmain.attributes['id'].nodeValue) // main

        // removeNamedItem()
        const oldArr = divmain.attributes.removeNamedItem('style')
        console.log(oldArr)  // style="color: red;"

        // attributes属性最有用的方法是迭代元素上所有的属性
        const outPutAttributes = Element => { 
            let pairs = []
            for (let i=0; i<Element.attributes.length; i++) { 
                const attribute = Element.attributes[i] 
                pairs.push(`${attribute.nodeName}="${attribute.nodeValue}"`)
            }
            return pairs
        }
        console.log(outPutAttributes(divmain)) // [name=value,....]
    </script>
</body>

</html>